//
//  BIDPersonalRepairViewController.m
//  HJGJCommunity
//
//  Created by mal on 2017/6/5.
//  Copyright © 2017年 mal. All rights reserved.
//
//故障类型
static NSString *faultTypeURL = @"client/repair/listRepairType.action";
//提交报修
static NSString *submitURL = @"client/repair/addPersonRepair.action";
//获取小区所有房屋分布
static NSString *allHouseListURL = @"client/repair/gainHouseList.action";

#import "BIDPersonalRepairViewController.h"
#import "BIDBrowserImageViewController.h"
#import "BIDFaultTypeViewController.h"
#import "ELCImagePickerHeader.h"
#import "BIDHousePickerView.h"
#import "BIDAddPhotoView.h"
#import "BIDCustomTextView.h"
#import "BIDUploadFile.h"

#import <MobileCoreServices/UTCoreTypes.h>

@interface BIDPersonalRepairViewController ()<BIDHousePickerViewDelegate, BIDAddPhotoViewDelegate, ELCImagePickerControllerDelegate, UINavigationControllerDelegate, BIDUploadFileDelegate, BIDFaultTypeViewControllerDelegate>
{
    //故障类型
    NSArray *_faultTypeArr;
    BIDHousePickerView *_housePickerView;
    BIDUploadFile *_uploadFile;
    //选中的故障类型
    NSString *_selectFaultTypeID;
    //
    NSString *_selectHouseCode;
    NSString *_selectHouseName;
}
@end

@implementation BIDPersonalRepairViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"个人报修";
    _faultTypeArr = [[NSArray alloc] init];
    _selectFaultTypeID = @"";
    _contentTextView.placeholder = @"简单描述下故障情况吧";
    _contentTextView.layer.borderWidth = 1.0f;
    _contentTextView.layer.borderColor = RGBACOLOR(239.f, 239.f, 239.f, 1.f).CGColor;
    _contentTextView.layer.cornerRadius = 3.f;
    _contentTextView.inputAccessoryView = self.toolBar;
    _phoneTF.inputAccessoryView = self.toolBar;
    _addPhotoView.delegate = self;
    //
    _uploadFile = [[BIDUploadFile alloc] initWithURL:[[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getPayServerAddr], submitURL]];
    _uploadFile.delegate = self;
    //
    [self fetchFaultType];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/**
 获取故障类型
 */
- (void)fetchFaultType
{
    NSString *strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getPayServerAddr], faultTypeURL];
    NSString *strPost = @"";
    [self sendHttpRequestWithURL:strRequestURL postData:strPost withCompletion:^(id obj, NSString *errMsg){
        if(errMsg)
        {
            [self showAlertView:errMsg buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        }
        else
        {
            if([obj isKindOfClass:[NSArray class]])
            {
                NSArray *arr = (NSArray *)obj;
                _faultTypeArr = [[NSArray alloc] initWithArray:arr];
            }
            [self fetchAllHouse];
        }
    }];
}

/**
 获取小区所有房屋分布
 */
- (void)fetchAllHouse
{
    NSString *strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getPayServerAddr], allHouseListURL];
    NSString *strPost = @"";
    [self sendHttpRequestWithURL:strRequestURL postData:strPost withCompletion:^(NSDictionary *responseDic, NSString *errMsg){
        if(!errMsg)
        {
            NSArray *arr = (NSArray *)responseDic;
            //_allHouseArr = [[NSMutableArray alloc] initWithArray:arr];
            //
            _housePickerView = [[BIDHousePickerView alloc] initWithMenuArr:arr];
            _housePickerView.bIsInputView = YES;
            _housePickerView.delegate = self;
            _houseCodeTF.inputView = _housePickerView;
        }
    }];
}
/**
 获取故障类型

 @param sender <#sender description#>
 */
- (IBAction)faultTypeBtnHandler:(id)sender
{
    BIDFaultTypeViewController *vc = [[BIDFaultTypeViewController alloc] initWithNibName:@"BIDFaultTypeViewController" bundle:nil];
    vc.faultTypeArr = [[NSArray alloc] initWithArray:_faultTypeArr];
    vc.delegate = self;
    if(_selectFaultTypeID.length > 0)
    {
        vc.faultTypeID = _selectFaultTypeID;
    }
    [self.navigationController pushViewController:vc animated:YES];
}

/**
 提交报修

 @param sender <#sender description#>
 */
- (IBAction)submitBtnHandler:(id)sender
{
    if(_faultTypeTF.text.length == 0)
    {
        [self showAlertView:@"请选择故障类型" buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        return;
    }
    if(_contentTextView.text.length == 0)
    {
        [self showAlertView:@"请填写报修内容" buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        return;
    }
    if(_houseCodeTF.text.length == 0)
    {
        [self showAlertView:@"请填写房号" buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        return;
    }
    if(_phoneTF.text.length == 0 || ![BIDGlobalMethods checkTelNumber:_phoneTF.text])
    {
        [self showAlertView:@"请填写有效的手机号码" buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        return;
    }
    
    NSString *strFaultTypeID = _selectFaultTypeID;
    NSString *strContent = _contentTextView.text;
    NSString *strHouseName = _houseCodeTF.text;
    NSString *strPhone = _phoneTF.text;
    if(_addPhotoView.imgArr.count > 0)
    {
        [_uploadFile addData:@"repairWeb.userId" value:[AppDelegate getUserId]];
        [_uploadFile addData:@"repairWeb.content" value:strContent];
        [_uploadFile addData:@"repairWeb.repairTele" value:strPhone];
        [_uploadFile addData:@"repairWeb.repairPlace" value:strHouseName];
        [_uploadFile addData:@"repairWeb.repairTypeId" value:strFaultTypeID];
        //
        for(int i=0; i<_addPhotoView.imgArr.count; i++)
        {
            UIImage *img = _addPhotoView.imgArr[i];
            NSData *imgData = UIImageJPEGRepresentation(img, 0.5f);
            NSString *strFileName = [[NSString alloc] initWithFormat:@"fileName%d.jpg", i];
            [_uploadFile addFileFromMemory:strFileName fieldName:@"uploadFile" data:imgData];
            [_uploadFile addData:@"uploadFileFile]Name" value:strFileName];
        }
        [_uploadFile finishAddFile];
        [_uploadFile startUpload];
    }
    else
    {
        NSMutableString *strPost = [NSMutableString string];
        [strPost appendFormat:@"repairWeb.userId=%@", [AppDelegate getUserId]];
        [strPost appendFormat:@"&repairWeb.content=%@", strContent];
        [strPost appendFormat:@"&repairWeb.repairPlace=%@", strHouseName];
        [strPost appendFormat:@"&repairWeb.repairTypeId=%@", strFaultTypeID];
        [strPost appendFormat:@"&repairWeb.repairTele=%@", strPhone];
        NSString *strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getPayServerAddr], submitURL];
        [self sendHttpRequestWithURL:strRequestURL postData:strPost withCompletion:^(NSDictionary *responseDic, NSString *errMsg){
            if(errMsg)
            {
                [self showAlertView:errMsg buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
            }
            else
            {
                [self showAlertView:@"提交成功" buttonTitle:ALERT_BTN_TITLE tag:@100 functionName:@"alertViewHandler"];
            }
        }];
    }
}

- (void)alertViewHandler
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - BIDUpladFileDelegate
- (void)finishUploadWithResult:(id)obj
{
    if([obj isKindOfClass:[NSDictionary class]])
    {
        NSDictionary *dic = (NSDictionary *)obj;
        NSNumber *value = dic[@"head"][@"success"];
        if([value intValue] == 1)
        {
            [self showAlertView:@"提交成功" buttonTitle:ALERT_BTN_TITLE tag:@100 functionName:@"alertViewHandler"];
        }
        else
        {
            [self showAlertView:@"提交失败" buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        }
    }
}

- (void)uploadFailedWithError:(NSError *)err
{
    [self showAlertView:[err localizedDescription] buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
}

#pragma mark - BIDFaultTypeViewControllerDelegate
- (void)selectFaultTypeID:(NSString *)typeID name:(NSString *)typeName
{
    _selectFaultTypeID = typeID;
    _faultTypeTF.text = typeName;
}

#pragma mark - BIDHousePickerViewDelegate
- (void)chooseHouseName:(NSString *)houseName houseCode:(NSString *)houseCode
{
    _selectHouseCode = houseCode;
    _selectHouseName = houseName;
    _houseCodeTF.text = houseName;
}

#pragma mark - BIDAddPhotoViewDelegate
- (void)choosePhoto
{
    if(_addPhotoView.imgArr.count == 3)
    {
        [self showAlertView:@"最多选择3张图片" buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        return;
    }
    //
    ELCImagePickerController *elcPicker = [[ELCImagePickerController alloc] initImagePicker];
    
    //3-_addPhotoView.imgArr.count
    elcPicker.maximumImagesCount = 111; //Set the maximum number of images to select to 100
    elcPicker.returnsOriginalImage = YES; //Only return the fullScreenImage, not the fullResolutionImage
    elcPicker.returnsImage = YES; //Return UIimage if YES. If NO, only return asset location information
    elcPicker.onOrder = YES; //For multiple image selection, display and return order of selected images
    elcPicker.mediaTypes = @[(NSString *)kUTTypeImage]; //Supports image and movie types((NSString *)kUTTypeMovie)
    
    elcPicker.imagePickerDelegate = self;
    
    [self presentViewController:elcPicker animated:YES completion:nil];
}

- (void)showPhotoAtIndex:(NSInteger)index withImgArr:(NSArray *)arr
{
    BIDBrowserImageViewController *vc = [[BIDBrowserImageViewController alloc] init];
    vc.index = index;
    vc.imgArr = arr;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)resizeViewWithFrame:(CGRect)frame
{
    _heightForPhotoViewConstraint.constant = CGRectGetHeight(frame);
    _heightForContainerViewConstraint.constant = CGRectGetMaxY(frame) + 8;//CGRectGetMinY(_addPhotoView.frame)+CGRectGetHeight(frame)+8;
    //[self.view layoutIfNeeded];
    CGSize contentSize = _scrollView.contentSize;
    contentSize.height = CGRectGetHeight(_containerView.frame);
    [_scrollView setContentSize:contentSize];
}

#pragma mark - ELCImagePickerControllerDelegate Methods

- (void)elcImagePickerController:(ELCImagePickerController *)picker didFinishPickingMediaWithInfo:(NSArray *)info
{
    [self dismissViewControllerAnimated:YES completion:nil];
    
    NSMutableArray *images = [NSMutableArray arrayWithCapacity:[info count]];
    for (NSDictionary *dict in info)
    {
        if ([dict objectForKey:UIImagePickerControllerMediaType] == ALAssetTypePhoto)
        {
            if ([dict objectForKey:UIImagePickerControllerOriginalImage])
            {
                UIImage* image=[dict objectForKey:UIImagePickerControllerOriginalImage];
                [images addObject:image];
                [_addPhotoView addPhoto:image];
            }
            else
            {
                NSLog(@"UIImagePickerControllerReferenceURL = %@", dict);
            }
        }
        else if ([dict objectForKey:UIImagePickerControllerMediaType] == ALAssetTypeVideo)
        {
            if ([dict objectForKey:UIImagePickerControllerOriginalImage])
            {
                UIImage* image=[dict objectForKey:UIImagePickerControllerOriginalImage];
                [images addObject:image];
            }
            else
            {
                NSLog(@"UIImagePickerControllerReferenceURL = %@", dict);
            }
        }
        else
        {
            NSLog(@"Uknown asset type");
        }
    }
    //_chosenImgArr = images;
}

- (void)elcImagePickerControllerDidCancel:(ELCImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end
